import Util from '../utils/util.js'
var Promise = require('../bluebird/index.js')
var common = require('../common/index.js')

var apiDomain = common.domain.apiDoamin

var ignoreMap = {
	20053: 1 // openid未绑定
}

function newAjaxPromise(name, data, type) {

	return new Promise(function(res, rej) {
		if(name == null || name === '') {
			rej('name is empty')
			return;
		}

		if(data == null) data = {};

		var sign = Util.md5(name) + 'SDFLKJSDFjjjs66993'
		if(data.user_id != null) {
			sign += Util.md5(data.user_id)
		}
		sign = Util.md5(sign)

		//		let cookie = Util.getStorage('cookie')
		//		let session_id = Util.getStorage('session_id')

		wx.request({
			method: type || "GET",
			data: {
				data: JSON.stringify(data),
				method: name,
				sign: sign
			},
			header: {
				//Accept: 'application/x.huaxm_businesses.v1+json',
				//'Content-type': 'application/x-www-form-urlencoded',
				//Authorization: 'Bearer ' + wx.getStorageSync('token'),
				//JSESSIONID: cookie || '',
				//'Mini-Program': '1'
			},
			url: apiDomain,
			success: function(resp) {
				if(resp.statusCode == 200 && (resp.data.code == 200)) {
					res(resp)
				} else {
//					var msgcode = resp.data.data.msgcode
					rej(resp.data)
				}
			},
			fail: function(resp) {
				var errMsg = resp.errMsg || JSON.stringify(resp)
				rej(errMsg)

			}
		});

	})
}

exports.post = function(name, data) {
	return newAjaxPromise(name, data, 'POST')
}

exports.get = function(name, data) {
	return newAjaxPromise(name, data, 'GET')
}

exports.wxPayment = function(data) {
	return new Promise(function(res, rej) {
		if(data == null || data.timeStamp == null || data.nonceStr == null || data.package == null || data.signType == null || data.paySign == null) {
			rej('at least one of payment param is empty')
			return;
		}
		wx.requestPayment({
			timeStamp: data.timeStamp + '',
			nonceStr: data.nonceStr + '',
			package: data.package + '',
			signType: data.signType + '',
			paySign: data.paySign + '',
			success: function(resp) {
				res()
			},
			fail: function(res) {
				rej('支付失败了')
			}
		})
	})
}